

//dateFile
var redis = require('redis');
var logger = require('./log4js.js');
var config = require('./config.json');
const RDS_OPTS  = {"auth_pass":config.RDS_PWD};

/*var redisPool = require('redis-connection-pool')('myRedisPool', {
    host: config.RDS_HOST, // default 
    port: config.RDS_PORT, //default 
    max_clients: 30, // defalut 
    perform_checks: true, // checks for needed push/pop functionality 
    database: config.DATA_BSAS, // database number to use 
    options: {
      auth_pass: config.RDS_PWD
    } //options for createClient of node-redis, optional 
  });*/




var ex = {};
ex.reload = 0;
//执行redis
ex.lpopRedis = function  (index,key,time,callback){
 	//创建客户端
	var	redisClient = redis.createClient(config.RDS_PORT,config.RDS_HOST,RDS_OPTS);
	redisClient.select(config.DATA_BSAS);
	function read(){
		var wait_time = 0;
		redisClient.brpop(key,100,function(err,reply){  //阻塞读取redis
			if(err != null){
				if(ex.reload > 5){
					logger.error('redis错误,重连大于5次，不再尝试');
					return;
				}
				ex.reload++;
				logger.warn('redis错误,进行重连');
				redisClient.quit();
				redisClient = redis.createClient(config.RDS_PORT,config.RDS_HOST,RDS_OPTS);
 				redisClient.select(config.DATA_BSAS);
				setTimeout(read,100);
				return;
			}
			//延迟时间处理
			if(reply != null){
				var r_data = reply[1];
				r_data = JSON.parse(r_data);
				if(r_data.time == undefined){
					wait_time = 0;
				}else{
					var now = Date.parse(new Date());
					var interval = now - r_data.time;
					if(interval > time){
						wait_time = 0;
					}else{
						wait_time = time-interval;
					}
				}
				//递归
				setTimeout(function(){
					callback(index,r_data);
					setTimeout(read,100);
				},wait_time);
				return;
			}
			setTimeout(read,100);
		});

	}
	redisClient.on('error',function(error){
		if(ex.reload > 5){
			logger.error('redis错误,重连大于5次，不再尝试');
			return;
		}
		ex.reload++;
		redisClient.quit();
		redisClient = redis.createClient(config.RDS_PORT,config.RDS_HOST,RDS_OPTS);
 		redisClient.select(config.DATA_BSAS);

 		setTimeout(read,100);
	});

	setTimeout(read,100);
	
}

//创建redis客户端
ex.redisClient = redis.createClient(config.RDS_PORT,config.RDS_HOST,RDS_OPTS);
//选择数据库
ex.redisClient.select(config.DATA_BSAS);

//左边插入数据
ex.lpush = function(key,val,callback){
	
 	ex.redisClient.lpush(key,val,function(err,res){
 		if(err != null){
	 		ex.redisClient.quit();
			ex.redisClient = redis.createClient(config.RDS_PORT,config.RDS_HOST,RDS_OPTS);
			ex.redisClient.select(config.DATA_BSAS);
 		}

 		callback(err,res);
 	});
};

ex.redisClient.on('error',function(error){
	ex.redisClient.quit();
	ex.redisClient = redis.createClient(config.RDS_PORT,config.RDS_HOST,RDS_OPTS);
	ex.redisClient.select(config.DATA_BSAS);
});

module.exports=ex; 



/*runRedis(KEY,function(reply){
	
});*/



//

